package com.glsc.ngateway.flowable.listener.global;

import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableCommentSupplement;
import com.glsc.ngateway.common.api.flowable.dto.Result;
import com.glsc.ngateway.flowable.amqp.InitQueue;
import com.glsc.ngateway.flowable.amqp.MessageSender;
import com.glsc.ngateway.flowable.constant.FlowableConstant;
import com.glsc.ngateway.flowable.service.feignservice.AmproductFeignService;
import com.glsc.ngateway.flowable.service.process.FlowableCommentSupplementService;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TaskCreateListener extends AbstractFlowableEngineEventListener {

    private static Logger logger = LoggerFactory.getLogger(TaskCreateListener.class);

    @Autowired
    private MessageSender sender;

    @Autowired
    private AmproductFeignService amproductFeignService;

    @Autowired
    private RuntimeService runtimeService;

    @Resource
    private FlowableCommentSupplementService flowableCommentSupplementService;


    @Override
    protected void taskCreated(FlowableEngineEntityEvent event) {
        logger.info("进入taskCreated监听器开始……");
        TaskEntity task = (TaskEntity) event.getEntity();
        logger.info("进入taskCreated监听器,{}", task);

        if (StringUtils.isEmpty(task.getParentTaskId())) {
            String msg = "当前节点:" + task.getName() + ", 执行人:" + task.getAssignee() + ", 任务id:" + task.getId() + ", 流程id:" + event.getProcessInstanceId() + ", 执行流id:" + task.getExecutionId();
            logger.info(msg);
            Map<String, Object> existvarmap = runtimeService.getVariables(task.getProcessInstanceId());
            logger.info("processId:" + event.getProcessInstanceId() + ", 已存在的流程变量:" + existvarmap.toString());
            sender.sendMessage(InitQueue.EXCHANGE, InitQueue.ROUTING_KEY, msg);


            //创建任务前，统一更新设置办理人和条件变量 //"taskAssignee\":{\"userGroup\":\"lm1,lm2\"}
            Map<String, String> taskAssigneeMap = (Map<String, String>) runtimeService.getVariable(task.getProcessInstanceId(), "taskAssignee");
            if (taskAssigneeMap != null) {
                for (Map.Entry<String, String> ass : taskAssigneeMap.entrySet()) {
                    if (!ass.getValue().contains(".")) {
                        String[] g = ass.getValue().split(",");
                        List<String> group = Arrays.stream(g).distinct().collect(Collectors.toList());
                        runtimeService.setVariable(task.getProcessInstanceId(), ass.getKey(), group);
                        runtimeService.setVariable(task.getProcessInstanceId(), ass.getKey() + "Size", group.size());
                    } else {
                        //包含.说明是角色
                        //amprod.role.产品经理
                        String sysid = ass.getValue().split(".")[0];
                        if (sysid.equals(FlowableConstant.AMPROD)) {
                            Result<List<String>> group = amproductFeignService.findAmProductUserIdList(ass.getValue());
                            if (group.getCode() == 10000) {
                                runtimeService.setVariable(task.getProcessInstanceId(), ass.getKey(), group.getData());
                                runtimeService.setVariable(task.getProcessInstanceId(), ass.getKey() + "Size", group.getData().size());
                            } else {
                                logger.error("进入processCreated监听器异常！" + group.toString());
                            }
                        }
                    }
                }
            }

            Map<String, String> conditionMap = (Map<String, String>) runtimeService.getVariable(task.getProcessInstanceId(), "conditionalVariable");
            if (conditionMap != null) {
                for (Map.Entry<String, String> co : conditionMap.entrySet()) {
                    runtimeService.setVariable(task.getProcessInstanceId(), co.getKey(), co.getValue());
                }
            }
        }

        try {
            FlowableCommentSupplement fcs = new FlowableCommentSupplement();
            fcs.setTaskId(task.getId());
            fcs.setProcessId(task.getProcessInstanceId());
            fcs.setTaskName(task.getName());
            fcs.setTaskAssignee(task.getAssignee());
            fcs.setTaskHandleStatus(FlowableConstant.FLOWABLE_TASK_HANDLE_STATUS_NONE);
            logger.info("进入taskCreated监听器,流程备注补充信息:{}", fcs);
            flowableCommentSupplementService.save(fcs);
        } catch (Exception e) {
            logger.error("进入processCreated监听器异常！", e);
        }

        logger.info("进入taskCreated监听器结束……");
        //  super.taskCreated(event);
    }

}